<template>
  <div id="questionnaire-update" class="clear">
    <div class="under-header-fixed-container">
      <div class="page-title-holder main-container container-limited flex content-space-between">
        <h2 class="page-title">问卷编辑</h2>
        <div>
          <el-button type="primary" size="small"
                     @click="onSubmit" :loading="isLoading">保存</el-button>
          <el-button size="small" class="m-r-10" @click="cancel">取消</el-button>
        </div>
      </div>
    </div>
    <div class="main-container container-fluid container-limited page-holder clear">
      <div v-if="Object.keys(questionnaire).length" class="questionnaire-paper paper-card">
        <div class="questionnaire-content">
          <el-input class="title" v-model="questionnaire.title" placeholder="编辑问卷标题"/>
          <el-input v-model="questionnaire.desc"
                    type="textarea" :rows="1" autosize class="desc m-t-24" placeholder="添加问卷说明"/>
          <Questions class="m-t-24" :questions.sync="questionnaire.questions"
                     :deleted-questions-id.sync="deletedQuestionsId" :editable="true"/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Questions from './Questions';
import * as format from './format';

export default {
  name: 'QuestionnaireUpdate', // 问卷编辑
  components: { Questions },
  data() {
    return {
      questionnaire: JSON.parse(JSON.stringify(this.$store.state.currentQuestionnaire)),
      deletedQuestionsId: [], // 被删除的问题的id
      isLoading: false, // 正在保存
    };
  },
  computed: {
    // 生成更新问卷所需参数
    initUpdateParams() {
      return {
        qnId: this.questionnaire.id,
        title: this.questionnaire.title || '未设置问卷标题',
        desc: this.questionnaire.desc,
        questions: format.formatQuestions(this.questionnaire.questions),
        deletedQuestionsId: this.deletedQuestionsId,
      };
    },
  },
  methods: {
    // 保存修改
    onSubmit() {
      this.isLoading = true;
      this.$api.questionnaires.update(this.initUpdateParams)
        .then((res) => {
          this.$message.success('保存成功');
          this.$router.push(`/${this.$rp.QUESTIONNAIRES}/${res.data.id}`);
        })
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
    // 取消并返回列表
    cancel() {
      this.$confirm('当前问卷未保存，是否取消编辑？', '提示', {
        customClass: 'confirm-left',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => this.$router.push(`/${this.$rp.QUESTIONNAIRES}`))
        .catch(() => {});
    },
  },
};
</script>

<style></style>
